<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="资讯标题" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入资讯标题" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100px" clearable>
              <el-option
                v-for="dict in dict.type.business_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plainicon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleOnline">上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleOffline">下架</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" prop="id" :show-overflow-tooltip="true" width="70" />
      <el-table-column label="资讯标题" prop="title" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="文描图" align="center" prop="file" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <el-image @click="bigImg(`${scope.row.file}`)" style="width: 120px; height: 120px; margin-bottom:-4px"
            :src="scope.row.file" :preview-src-list="srcList"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="首页是否显示" align="center" key="ifIndex" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.ifIndex" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="70"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="scope.row.status !== '1'" size="mini" type="text" icon="el-icon-upload2" @click="handleOnline(scope.row)">上架</el-button>
          <el-button v-if="scope.row.status === '1'" size="mini" type="text" icon="el-icon-download" @click="handleOffline(scope.row)">下架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="1000px" append-to-body>
      <div class="product_info">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="20">
              <el-form-item label="资讯标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入资讯标题" :maxlength="30" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="23">
              <el-form-item label="资讯内容" prop="content">
                <myeditor v-model="form.content" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="23">
              <el-form-item label="资讯图片" prop="file">
                <fileImg :patentfile="form.file" @saveFile="getFile" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="23">
              <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listIndustry, upateIfIndex, delNews, getNews, addIndustry, updateNews, batchUpdateStatus, updateStatus } from "@/api/news/concern";  //导入consult.js文件路径

export default {
  name: "News",
  dicts: [
    'business_status',
  ],
  components: {
    fileImg: () => import('./fileImg'),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行业表格数据
      newsList: [],
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 日期范围
      dateRange: [],
      srcList: ["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "资讯标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "资讯内容不能为空", trigger: "blur" }
        ],
        file: [
          { required: true, message: "资讯图片不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询行业列表 */
    getList() {
      this.loading = true;
      this.newsList = [];
      listIndustry(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        let imgSrc = response.rows;
        if (imgSrc !== undefined && imgSrc.length > 0) {
          for (let i = 0; i < imgSrc.length; i++) {
            const patent = imgSrc[i];
            patent['file'] = process.env.VUE_APP_BASE_API + patent['file'];
            this.newsList.push(patent);
          }
        }
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        content: undefined,
        file: undefined,
        sort: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资讯";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getNews(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资讯";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除行业编号为"' + id + '"的数据项？').then(function () {
        return delNews(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    // 是否在首页显示开关修改
    handleStatusChange(row) {
      let text = row.ifIndex === "1" ? "是" : "否";
      this.$modal.confirm('是否要在首页显示"' + text).then(function () {
        if (row.ifIndex === '1' && row.status !== '1') {
          this.$modal.msgError("设置首页展示必须是上架状态");
          return;
        }
        return upateIfIndex(row.id, row.ifIndex);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.ifIndex = row.ifIndex === "0" ? "1" : "0";
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateNews(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIndustry(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    getFile(fileUrl) {
      this.form.file = fileUrl;
    },
    /*getText(text) {
      this.form.remark = text;
    },*/
    bigImg(url) {
      this.srcList[0] = url;
    },
    handleOnline(row) {
      // 上架
      if (row.id !== undefined) {
        // 单个
        if(row.file === undefined) {
          this.$modal.msgError('上架新闻前必须设置封面图');
          return;
        }
        updateStatus({'id':row.id, 'status':'1'}).then(() => {
          this.$modal.msgSuccess('上架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateStatus({'ids':this.ids, 'status':'1'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要上架的新闻");
      }
    },
    handleOffline(row) {
      // 下架
      if (row.id !== undefined) {
        // 单个
        updateStatus({'id':row.id, 'status':'2'}).then(() => {
          this.$modal.msgSuccess('下架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateStatus({'ids':this.ids, 'status':'2'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要下架的新闻");
      }
    },
  }
}
</script>

<style scoped lang="scss">
.product_info {
  height: 500px;
  overflow-y: auto;
}
</style>
